<template>
  <div>
    <FixedOperation>
      <!-- 内容 -->
      <el-row :gutter="20">
        <!--产品分类-->
        <el-col :span="24" :xs="24">
          <div class="text-right">
            <slot></slot>
            <el-button
              type="primary"
              plain
              @click="handleSubmit('examine')"
              v-if="isExamine && isCanStart"
              >发起申请</el-button
            >
            <el-button
              v-hasPermi="['system:notice:submit']"
              type="primary"
              @click="handleSubmit('save')"
              v-show="!formDisabled"
              >发布</el-button
            >
            <el-button
              type="primary"
              plain
              @click="viewProcess"
              v-if="proInsId"
            >
              查看流程</el-button
            >
            <el-button type="primary" plain @click="handleReturn"
              >返回</el-button
            >
            <!-- <el-button icon="Refresh" @click="handleReset(form)"
              >重置</el-button
            > -->
          </div>
        </el-col>
      </el-row>
    </FixedOperation>
    <div class="app-container notice-form">
      <el-form
        ref="form"
        :model="formData"
        label-width="140px"
        :disabled="formDisabled"
        :rules="formRules"
      >
        <el-row>
          <el-col :span="13" :offset="4">
            <el-form-item label="公告标题" prop="title">
              <el-input v-model="formData.title" placeholder="公告标题" />
            </el-form-item>
          </el-col>
          <el-col :span="13" :offset="4">
            <el-form-item label="公告类型" prop="announcementType">
              <el-tree-select
                class="w-full"
                v-model="formData.announcementType"
                placeholder="公告类型"
                :data="announcementType"
              /><!-- 
                check-strictly -->
            </el-form-item>
          </el-col>
          <el-col :span="13" :offset="4">
            <el-form-item label="发文部门" prop="department">
              <el-input v-model="formData.department" placeholder="发文部门" />
            </el-form-item>
          </el-col>
          <el-col :span="13" :offset="4">
            <el-form-item label="摘要" prop="summary">
              <el-button
                type=""
                link
                :icon="isShow ? 'ArrowUp' : 'ArrowDown'"
                @click="isShow = !isShow"
                >{{ isShow ? '收起' : '展开' }}</el-button
              >
              <editor
                v-show="isShow"
                class="w-full"
                v-model="formData.summary"
                :min-height="192"
              />
            </el-form-item>
          </el-col>
          <el-col :span="13" :offset="4">
            <el-form-item label="公告正文" prop="detail"
              ><!-- 
                v-model:file-list="formData.detail" -->
              <el-upload
                class="upload-demo"
                action="#"
                :before-upload="beforeAvatarUpload"
                :http-request="requestFile"
                accept=" .doc, .docx, .pdf"
                :limit="1"
                :show-file-list="false"
                v-if="formData.detail.length == 0"
              >
                <el-button type="default" style="font-size: 14px"
                  ><el-icon><UploadFilled /></el-icon>上传正文</el-button
                >
                <!-- <template #tip>
                  <div class="el-upload__tip float-right">
                    支持格式.doc .docx .pdf ，单个文件不能超过200MB
                  </div>
                </template> -->
              </el-upload>
              <div class="text-14px w-full" v-else>
                <div v-for="item in formData.detail" :key="item.fileName">
                  <el-link
                    :underline="false"
                    type="primary"
                    @click="viewFiles(item.url)"
                    >{{ item.origFileName }}</el-link
                  >
                  <el-button text plain @click="delFileName(item.fileName)"
                    >删除</el-button
                  >
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="13" :offset="4">
            <el-form-item label="公告附件" prop="attachment">
              <!-- 
                v-model:file-list="formData.attachment" -->
              <el-upload
                class="upload-demo"
                action="#"
                :before-upload="beforeAvatarUpload1"
                :http-request="requestFile1"
                accept=".rar, .zip, .doc, .docx, .pdf, .xls, .xlsx, .ppt, .pptx,
                    .gif, .jpg, .jpeg, .png"
                :limit="10"
                :show-file-list="false"
              >
                <el-button type="default" style="font-size: 14px"
                  ><el-icon><UploadFilled /></el-icon>上传附件</el-button
                >
                <!-- <template #tip>
                  <div class="el-upload__tip float-right">
                    支持格式.rar .zip .doc .docx .pdf .xls .xlsx .ppt .pptx .gif
                    .jpg .jpeg .png ，单个文件不能超过200MB
                  </div>
                </template> -->
              </el-upload>
              <div class="text-14px mt-10px" style="width: 100%">
                <div
                  v-for="(item, index) in formData.attachment"
                  :key="item.fileName"
                >
                  <el-link :href="item.url" :underline="false" type="primary">{{
                    item.origFileName
                  }}</el-link>
                  <el-button text plain @click="delFileName1(index)"
                    >删除</el-button
                  >
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="13" :offset="4">
            <el-form-item label="原文件链接" prop="originalLink">
              <el-input
                v-model="formData.originalLink"
                placeholder="原文件链接"
              />
            </el-form-item>
          </el-col>
          <el-col :span="13" :offset="4">
            <el-form-item label="接收人员" prop="receiveType">
              <el-radio-group v-model="formData.receiveType">
                <el-radio-button
                  v-for="item in receive_type"
                  :key="item.value"
                  :label="item.value"
                  >{{ item.label }}</el-radio-button
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="13" :offset="4">
            <el-form-item
              prop="_receiveUserArr"
              label="指定人员"
              v-if="showUser"
            >
              <el-select
                class="w-full"
                v-model="formData._receiveUserArr"
                :multiple="true"
                placeholder="指定人员"
                @focus="selectUserFn('receiveUserArr')"
              >
                <el-option
                  v-for="item in userOption['receiveUserArr']"
                  :key="item.uuid"
                  :label="item.label"
                  :value="item.uuid"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="13" :offset="4">
            <el-form-item prop="groupIdArr" label="指定分组" v-if="showGroup">
              <el-input
                v-model="formData.groupNameArr"
                @focus="selectGroupFn()"
                clearable
                @clear="
                  () => {
                    formData.groupNameArr = []
                    formData.groupIdArr = []
                  }
                "
                placeholder="指定分组"
              />

              <!-- <el-select
                class="w-full"
                v-model="formData._receiveUserArr"
                :multiple="true"
                placeholder="指定人员"
                @focus="selectUserFn('receiveUserArr')"
              >
                <el-option
                  v-for="item in userOption['receiveUserArr']"
                  :key="item.uuid"
                  :label="item.label"
                  :value="item.uuid"
                ></el-option>
              </el-select> -->
            </el-form-item>
          </el-col>
          <el-col :span="13" :offset="4">
            <el-form-item label="发布时间" prop="publishTime">
              <el-date-picker
                style="width: 100%"
                v-model="formData.publishTime"
                type="datetime"
                placeholder="发布时间"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 人员弹出框下拉框 -->
    <SelectDialog
      :dialog-param="dialogParam"
      @ok="selectDialogData"
      @close="
        val => {
          dialogParam.isDialog = false
        }
      "
    />

    <!-- 提交审批 -->
    <SubmissionProcess
      :dialog-param="examineParam"
      :flowOptions="flowOptions"
      @initiate="handleClose('initiate')"
      @close="handleClose('examine')"
    ></SubmissionProcess>

    <!-- 分组弹出框 -->
    <PersonnelGroup
      v-model:open="groupParams.open"
      :groupConfig="groupParams"
      @ok="selectedFn"
    />
  </div>
</template>
<script setup name="NoticeForm">
import { useRouter, useRoute } from 'vue-router'
import FixedOperation from '@/components/FixedOperation'
import useCommonStore from '@/store/modules/common'
import useUserStore from '@/store/modules/user'
import {
  getNotice,
  setNotice,
  noticeUpFiles,
  noticeDelFile
} from '@/api/system/notice'
import useTagsViewStore from '@/store/modules/tagsView'
import {
  skipToError,
  getTreeNodeByParam,
  getPricipalId,
  viewFile
} from '@/utils/commo'
import SubmissionProcess from '@/businessComponents/SubmissionProcess'
import {
  listProcess,
  getBusinessProStatus,
  getNodeData
} from '@/api/workflow/process'
import { getUserProfile } from '@/api/system/user'

const router = useRouter()
const route = useRoute()
const commonStore = useCommonStore()
const { proxy, type } = getCurrentInstance()
const companyData = ref([])
commonStore.getCompanyData().then(e => {
  companyData.value = e
})

const examineParam = ref({}) // 传递的参数
const isExamine = ref(true) // 判断是否走审批按钮
const flowOptions = ref([]) // 该业务的流程数据
const isCanStart = ref(true) // 判断该业务是否可以审批发起 以及办理详情 访问的时候不能审批 ===》针对编辑页面  办理详情

const { announcement_type, receive_type } = proxy.useDict(
  'announcement_type', //  --公告类型
  'receive_type' //  --接收类型
)

const props = defineProps({
  noticeData: {
    type: Object,
    require: false,
    default: null
  },
  noticeId: {
    type: [Number, String],
    require: true
  },
  id: {
    type: [Number, String],
    require: false
  }
})

const announcementType = ref(
  computed(() => {
    if (announcement_type.value.length > 0) {
      let types = toRaw(announcement_type.value)
      return proxy.handleTree(types, 'value')
      // console.log('businessTypeOption.value==>', businessTypeOption.value)
    }
  })
)
const showUser = ref(
  computed(() => {
    return formData.value.receiveType == '4' //指定人时显示
  })
)
const showGroup = ref(
  computed(() => {
    return formData.value.receiveType == '5' //指定人时显示
  })
)
const data = reactive({
  formData: {
    attachment: [], //附件
    receiveType: '1',
    publishTime: proxy.parseTime(new Date(new Date().getTime())),
    detail: [] //正文
  },
  userOption: { publishUsers: [] }, //人员选择下拉
  formRules: {
    title: [
      {
        required: true,
        message: '请输入公告标题',
        trigger: 'blur'
      }
    ],
    department: [
      {
        required: true,
        message: '请输入发文部门',
        trigger: 'blur'
      }
    ],
    announcementType: [
      {
        required: true,
        message: '请选择公告类型',
        trigger: 'change'
      }
    ],
    detail: [
      {
        required: true,
        message: '请上传公告正文',
        trigger: ['blur', 'change']
      }
    ],
    publishTime: [
      {
        required: true,
        message: '请选择发布时间',
        trigger: ['blur', 'change']
      }
    ],
    _receiveUserArr: [
      {
        required: true,
        message: '请选择指定人员',
        trigger: ['change']
      }
    ],
    groupIdArr: [
      {
        required: true,
        message: '请选择指定组',
        trigger: ['blur', 'change']
      }
    ]
  },
  dialogParam: {},
  isShow: false, //判断摘要是否展示
  formDisabled: false, // 禁用表单
  bpmnStatus: '', //表单标题
  proInsId: '', //流程实例id
  postGroup: ''
})
const {
  formData,
  userOption,
  formRules,
  dialogParam,
  isShow,
  formDisabled,
  bpmnStatus,
  proInsId,
  postGroup
} = toRefs(data)

watch(
  [() => route.query.noticeId, () => props.id],
  async () => {
    if (route.query.noticeId && route.name == type.name) {
      getFormData(route.query.noticeId)
    } else if (props.id && route.name == 'WorkDetail') {
      await getFormData(props.id)
      // 获取流程节点数据
      if (route.query.processed) {
        // fieldDisabled.value
        let res = await getNodeData(props.id)
        if (res.code !== 200) return
        bpmnStatus.value = res.data?.nowTaskName
        formDisabled.value =
          res.data == null || res.data?.isFirst == 'Y' ? false : true
      }
      isCanStart.value = false
    } else if (props.noticeId && route.name == 'EditNotice') {
      if (route.query.proInsId) {
        proInsId.value = route.query.proInsId
      }
      await getFormData(props.noticeId)
      //根据业务查询审批状态
      await getBusinessProStatusFn()
      // 判断表单是否可编辑  获取当前流程节点
      let res = await getNodeData(props.noticeId)
      bpmnStatus.value = res.data?.nowTaskName
      formDisabled.value =
        res.data == null || res.data?.isFirst == 'Y' ? false : true
    } else if (route.name == type.name) {
      isExamine.value = true
      // 走业务流程
      initFlowFn('27')
    }
  },
  {
    immediate: true
  }
)
// 初始化
function init() {
  getUserProfile().then(ref => {
    postGroup.value = ref.postGroup
  })
}
/** 获取产品详情
 * @param {number}  id 表单id
 */
async function getFormData(id) {
  proxy.$modal.loading('加载中')
  let res = await getNotice(id)
  if (res.code !== 200) return
  let resData = {}
  resData = res.data
  formData.value = resData
  // 获取发布员
  if (formData.value.receiveUserArr) {
    await getDefaultUserInfo(
      formData.value.receiveUserArr,
      '_receiveUserArr',
      'receiveUserArr'
    )
  }
  proxy.$modal.closeLoading()
}
// 保存
function handleSubmit(type) {
  if (
    formData.value._receiveUserArr &&
    formData.value._receiveUserArr.length > 0
  ) {
    formData.value.receiveUserArr = getPricipalId(
      userOption.value['receiveUserArr'],
      formData.value._receiveUserArr
    )
  }
  return new Promise((resolve, reject) => {
    proxy.$refs.form.validate(async (valid, done, msg) => {
      if (valid) {
        let res = await setNotice({
          ...formData.value,
          nowPublish: type == 'save'
        })
        if (res.code !== 200) {
          reject(res)
          return
        }
        resolve(res)
        await getFormData(res.data.id)
        // 审批流程id赋值
        examineParam.value.businessId = res.data.id
        if (type == 'examine') {
          handleExamine()
        } else if (type == 'save') {
          proxy.useReturn(
            '',
            () => {
              //返回上一步
              handleReturn()
            },
            async () => {
              //继续
            }
          )
        }
      }
    })
  })
}
// 流程同意调用的方法
async function handleSave() {
  if (!formDisabled.value) {
    return await handleSubmit()
  }
}

function handleReturn() {
  useTagsViewStore().delView(router.currentRoute.value)
  router.go(-1)
  // router.push({ path: url, query: data })
  //   proxy.$refs.form.clearValidate()
}
/***************************业务流程 模块 start****************************************************************/
/*****审批模块  start*** */
/**
 * 提交审批 按钮
 发布需要的参数 examineParam 参数说明
  visible弹出框是否显示
  businessId //业务id
  businessName//业务名称（如：项目模块 businessName：项目名称）
  amount// 流程设计里面设计的条件参数值
  categoryCode //==>流程分类 页面查看 分类编码：项目1，订单2 客户3 	投标4 采购13 销售14 通知公告 27
/**
 * 提交审批 按钮
 */
const handleExamine = async () => {
  if (!examineParam.value.businessId) {
    proxy.$modal.msgWarning('请重新发起审批')
    return false
  }
  examineParam.value.businessName = formData.value.title //标题
  examineParam.value.isLeader = postGroup.value.includes('部门经理')
  examineParam.value.categoryCode = '27' //分类编码：项目1，订单2 客户3 	投标4
  examineParam.value.visible = true
}
// 关闭
const handleClose = type => {
  switch (type) {
    case 'examine':
      //弹出框关闭
      examineParam.value.visible = false
      break
    case 'initiate':
      //审批 发起成功
      isCanStart.value = false
      examineParam.value.visible = false
      handleReturn()
      break
  }
}
/*****审批模块  end*** */
/**
 * 业务流程整体思路：
 * 1.查询该业务是否有流程
 * 2.根据该业务流程来判断
 * * 2.1没有流程-提示不能新建数据
 * 3.点击发起申请【调组件】
 * * 只有一条流程时，下一环节人的显示 -再发起
 * * 多条流程时，选择流程，再选下一环节人的显示 -再发起
 * @param {*} type  业务类型 项目是1 订单业务2 	客户模块业务3 采购13
 */

async function initFlowFn(type) {
  // 1.查询该业务是否有流程
  let comRes = await listProcess({
    pageNum: 1,
    pageSize: 9999,
    category: type
  })
  flowOptions.value = comRes.rows || []
  // 2.根据
  if (JSON.stringify(flowOptions.value) == '[]') {
    //2.1 没有流程-提示不能新建数据
    if (route.name == type.name) {
      // 新建页面
      proxy.$modal.msgError('该业务没有配置流程，请先创建流程')
    } else {
      //编辑页面
      isExamine.value = false
    }
  } else {
    isExamine.value = true
  }
}
// 编辑页面的时候 -》根据业务查询审批状态
async function getBusinessProStatusFn() {
  let statusRes = await getBusinessProStatus({ businessId: formData.value.id })
  if (statusRes.data.canStart) {
    // canStart false时 不能发起，true则可以发起
    isCanStart.value = true
    initFlowFn('27')
  } else {
    isCanStart.value = false
  }
  // if (statusRes.data.status) {
  //   // status判断流程环节05表示结束
  //   isCanStart.value = true
  // } else {
  //   isCanStart.value = false
  // }
}
/***************************业务流程 模块 end****************************************************************/

/**文件上传 限制条件
 *
 * @param {*} rawFile
 */
function beforeAvatarUpload(rawFile) {
  const ext = rawFile.name.substring(rawFile.name.lastIndexOf('.'))
  const allowType = ['.doc', '.docx', '.pdf'].indexOf(ext) > -1
  const isLt2M = rawFile.size / 1024 / 1024 < 200

  if (!allowType) {
    proxy.$message.error('上传文件只能是doc、docx、pdf格式!')
  } else if (!isLt2M) {
    proxy.$message.error('上传文件大小不能超过 200MB!')
  }
  return allowType && isLt2M
}
// 上传文件
function requestFile(params) {
  let uploadData = new FormData()
  uploadData.append('file', params.file)
  uploadData.append('bucketName', 'article')
  noticeUpFiles(uploadData).then(res => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess(`${res.data.origFileName}上传成功`)
      formData.value.detail = [res.data]
    }
  })
}
// 删除正文
async function delFileName(name) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      let fule = {
        bucketName: 'article',
        fileName: name
      }
      const res = await noticeDelFile(fule)
      if (res.code === 200) {
        formData.value.detail = []
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    proxy.$modal.msgError(error)
  }
}
/**文件上传 限制条件
 *
 * @param {*} rawFile
 */
function beforeAvatarUpload1(rawFile) {
  if (rawFile.size / 1024 / 1024 > 200) {
    proxy.$modal.msgError('单个文件不能超过200MB!')
    return false
  }
}
// 上传附件
function requestFile1(params) {
  console.log('formData.value.attachment==>', formData.value.attachment)
  let uploadData = new FormData()
  uploadData.append('file', params.file)
  uploadData.append('bucketName', 'article')
  noticeUpFiles(uploadData).then(res => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess(`${res.data.origFileName}上传成功`)
      formData.value.attachment.push(res.data)
      console.log('formData.value.attachment==>', formData.value.attachment)
    }
  })
}
// 删除附件
async function delFileName1(index) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      let fule = {
        bucketName: 'article',
        fileName: formData.value.attachment[index].fileName
      }
      const res = await noticeDelFile(fule)
      if (res.code === 200) {
        formData.value.attachment.splice(index, 1)
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    proxy.$modal.msgError(error)
  }
}
// 预览文件
function viewFiles(url) {
  viewFile(url, useUserStore().userInfo.nickName)
}

/**
 * 人员选择
 * @param keyName handleId:经办人  receiveUserArr:业务员
 */
function selectUserFn(keyName) {
  switch (keyName) {
    case 'receiveUserArr':
      dialogParam.value.type = keyName
      dialogParam.value.title = '请选择业务员'
      dialogParam.value.isDialog = true
      dialogParam.value.multiple = true
      dialogParam.value.checkStrictly = false
      dialogParam.value.apiParams = {
        disabled: 'false',
        deptId:
          useUserStore().user['orgId'] == '484'
            ? undefined
            : useUserStore().user['orgId']
      }

      dialogParam.value.nodeKey = 'uuid'
      dialogParam.value.defaultCheckedKeys = formData.value['_' + keyName]
      dialogParam.value.dataType = 'person'
      break
  }
}

// 人员选择确定
const selectDialogData = val => {
  switch (val.type) {
    case 'receiveUserArr':
      userOption.value.receiveUserArr = val.selectData
      // formData.value.transactionName = val.labelData.toString()
      formData.value._receiveUserArr = val.defaultCheckedKeys
      break
    /* case 'receiveUserArr':
      userOption.value.receiveUserArr = val.selectData
      formData.value.receiveUserArr = val.defaultCheckedKeys
      break */
  }
}

/**
 * 根据当前用户id转为uuid（id前加u）
 * @param val 输入用户的id
 * @param fieldName 需要赋值的字段
 * @param selectArr 用户的字典
 */
async function getDefaultUserInfo(val, fieldName, selectArr) {
  let userTree = await commonStore.getUseTreeData()
  userOption.value[selectArr] = []
  let id = ''
  if (val) {
    id = val
  }
  if (Array.isArray(id)) {
    formData.value[fieldName] = []
    id.forEach(item => {
      let obj = getTreeNodeByParam(userTree, item, 'id', [])
      try {
        userOption.value[selectArr].push(...obj)
        formData.value[fieldName].push(obj[0].uuid)
      } catch (error) {
        console.log('error用户uuid错误==>', error)
      }
    })
  } else {
    //根据当前用户id获取uuid
    let obj = getTreeNodeByParam(userTree, id, 'id', [])
    userOption.value[selectArr] = obj
    formData.value[fieldName] = obj[0].uuid
  }
}

//查看流程
function viewProcess() {
  router.push({
    path: '/process/workDetail',
    query: {
      procInsId: proInsId.value,
      //   taskId: row.taskId,
      processed: false
    }
  })
}

// 分组参数
const groupParams = ref({
  open: false
})
// 打开分组
const selectGroupFn = () => {
  groupParams.value = {
    open: true,
    defaultSelect:
      formData.value.groupIdArr && formData.value.groupIdArr.length > 0
        ? formData.value.groupIdArr.map((item, index) => {
            return {
              businessId: item,
              businessName: formData.value.groupNameArr[index]
            }
          })
        : []
  }
}
// 选定分组
const selectedFn = val => {
  formData.value.groupIdArr = val.value.map(item => item.businessId)
  formData.value.groupNameArr = val.value.map(item => item.businessName)
  console.log('val==>', val)
}

//暴露出保存方法
defineExpose({ handleSave })

init()
</script>
<style scoped>
.form-title {
  color: #111111;
}
.notice-form:deep(.form-title:before) {
  content: '▋';
  display: inline-block;
  color: #409eff;
}
:deep(.avue-crud__empty) {
  padding: 0;
}
</style>
